import 'package:dio/dio.dart';
import 'package:fsharing/core/models/cart_add.dart';
import 'package:fsharing/core/models/product_detail.dart';
import 'package:fsharing/core/services/api.dart';
import 'package:fsharing/core/viewmodels/view_model.dart';

/// 立即购买
class BuyNowModel extends ViewModel {
  final Api api;
  Map<String, int> _cartIdQuantity;
  String _errorMessage;

  BuyNowModel(this.api) : super();

  Map<String, int> get cartIdQuantity => _cartIdQuantity;

  String get errorMessage => _errorMessage;

  Future<ViewState> buyNow(ProductDetail productDetail, CartAdd cartAdd) async {
    viewState = ViewState.busy;
    try {
      // 添加到购物车
      // CartAdd cartAdd = await api.cartAdd(
      //   miaId,
      //   quantity,
      //   productDetail.referStoreId,
      // );
      // 检查可否下单
      _cartIdQuantity = {'${cartAdd.cartId}': cartAdd.quantity};
      await api.orderCheck(_cartIdQuantity);
      viewState = ViewState.success;
    } catch (e) {
      _errorMessage = e is DioError ? e.message : e.toString();
      viewState = ViewState.error;
    }
    return viewState;
  }
}
